<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="针筒卡号" v-if="permissionStore.hasPermisson('ztsbwh.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.dropDownData"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="采购部门" v-if="permissionStore.hasPermisson('ztsbwh.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.dropDownData1"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="固定资产编号" v-if="permissionStore.hasPermisson('ztsbwh.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.fixedAssetsCode"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
          >
          </Toolbar>
        </div>
      </div>

      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <div :style="{ height: '100%', padding: '10px' }">
          <div style="width: 100%; height: 100%">
            <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
          </div>
        </div>
      </a-spin>
    </template>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      unmount-on-close
      popup-container=".arco-tabs-content"
      height="100%"
      :visible="pageData.showAdd"
      :ok-loading="pageData.pageLoading"
      placement="bottom"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.isDetails == true ? '详情' : pageData.sideTitle }}
      </template>
      <template #footer>
        <a-button @click="pageData.showAdd = false"> 关闭</a-button>
        <a-button type="primary" @click="sideOk" v-if="!pageData.isDetails"> 保存</a-button>
      </template>
      <div style="text-align: right; margin-bottom: 5px"> </div>
      <div style="width: 100%; height: 100%; overflow: auto">
        <el-scrollbar style="height: 30%">
          <a-form
            ref="formRef"
            layout="inline"
            :model="dataForm"
            size="mini"
            :label-col-props="{ span: 10 }"
            :wrapper-col-props="{ span: 14 }"
          >
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="针筒卡号"
              field="cylinderCardNumber"
              :disabled="pageData.isDetails"
              :rules="[{ required: true, message: '针筒卡号必填' }]"
              :validate-trigger="['change', 'blur']"
            >
              <a-input class="bacClass" v-model="dataForm.cylinderCardNumber" />
            </a-form-item>
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="适用机型"
              field="applicableModels"
              :rules="[{ required: true, message: '适用机型' }]"
            >
              <a-select
                popup-container="html"
                class="bacClass"
                allow-search
                allowClear
                :loading="loading1"
                @search="handleSearch13"
                :filter-option="false"
                v-model.trim="dataForm.applicableModels"
                @focus="focusSel13"
                :disabled="pageData.isDetails"
                :validate-trigger="['change', 'blur']"
              >
                <a-option v-for="item in pageData.nameList13" :value="item">{{ item }}</a-option>
              </a-select>
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="针筒编码"
              field="workDrumCode"
              :rules="[{ required: true, message: '针筒编码必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input class="bacClass" v-model="dataForm.workDrumCode" />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="寸数"
              field="smallNumber"
              :rules="[{ validator: isChiese }, { required: true, message: '寸数必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input-number
                v-model="dataForm.smallNumber"
                @change="getModel"
                class="bacClass"
                :precision="0"
              />
            </a-form-item>
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="针数"
              field="numberThreads"
              :rules="[{ validator: isChiese1 }, { required: true, message: '针数必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input-number
                v-model="dataForm.numberThreads"
                @change="getModel"
                class="bacClass"
                :precision="1"
              />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="总针数"
              field="sumNeedleNum"
              :rules="[{ validator: isChiese1 }, { required: true, message: '总针数必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input-number
                v-model="dataForm.sumNeedleNum"
                @change="getModel"
                class="bacClass"
                :precision="0"
              />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="型号"
              field="model"
              :rules="[{ required: true, message: '型号必填' }]"
              disabled
              :validate-trigger="['change', 'blur']"
            >
              <a-input v-model="dataForm.model" class="bacClass" />
            </a-form-item>
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="存放位置"
              field="placeStorage"
              :rules="[{ required: true, message: '存放位置必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input class="bacClass" v-model="dataForm.placeStorage" />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="适用针型"
              field="applyPin"
              :rules="[{ required: true, message: '适用针型必填' }]"
              :disabled="pageData.isDetails"
              :validate-trigger="['change', 'blur']"
            >
              <a-input class="bacClass" v-model="dataForm.applyPin" />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="采购公司"
              field="useFrim"
              :rules="[{ required: true, message: '公司必填' }]"
              :disabled="pageData['useFrim']"
              :validate-trigger="['change', 'blur']"
            >
              <a-cascader
                v-model="dataForm.useFrim"
                :options="pageData.firmGroupList"
                allow-clear
                ref="casOb"
                @change="cascaderChange($event, dataForm.useFrim)"
                class="bacClass"
                :title="pageData.title"
                :disabled="pageData.isDetails"
                popup-container="html"
              />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="采购部门"
              field="applyBranch"
              :rules="[{ required: true, message: '采购部门必填' }]"
              :disabled="pageData['applyBranch']"
              :validate-trigger="['change', 'blur']"
            >
              <a-cascader
                v-model="dataForm.applyBranch"
                :options="pageData.bmList"
                allow-clear
                ref="casOb1"
                class="bacClass"
                :disabled="dataForm.useFrim == null || dataForm.useFrim == '' || pageData.isDetails"
                @change="cascaderChange1"
                :class="{ bacClass: !(dataForm.useFrim == null || dataForm.useFrim == '') }"
                :title="pageData.title1"
                popup-container="html"
              />
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label-col-flex="100px" label="品牌名称">
              <a-select
                popup-container="html"
                :style="{ width: '300px' }"
                :loading="loading"
                @search="handleSearch12"
                class="bacClass"
                v-model="dataForm.brand"
                :filter-option="false"
                allow-search
                allow-clear
                @focus="focusSel12"
                :disabled="pageData.isDetails"
              >
                <a-option v-for="item in pageData.nameList12" :value="item">{{ item }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="产地"
              field="place"
              :disabled="pageData.isDetails"
            >
              <a-input class="bacClass" v-model="dataForm.place" />
            </a-form-item>
            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="固定资产编号"
              field="fixedAssetsCode"
              :disabled="pageData.isDetails"
            >
              <a-input class="bacClass" v-model="dataForm.fixedAssetsCode" />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="编制日期"
              field="compileDate"
              :disabled="pageData.isDetails"
            >
              <a-date-picker
                popup-container="html"
                :style="{ width: '300px' }"
                class="bacClass"
                v-model="dataForm.compileDate"
              />
            </a-form-item>

            <a-form-item
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="生产日期"
              field="scDate"
              :disabled="pageData.isDetails"
            >
              <a-date-picker
                popup-container="html"
                :style="{ width: '300px' }"
                class="bacClass"
                v-model="dataForm.scDate"
              />
            </a-form-item>
            <a-form-item
              v-if="pageData.sideTitle == '修改针筒设备维护'"
              :style="{ width: '355px' }"
              label-col-flex="100px"
              label="等级"
            >
              <a-select
                :disabled="pageData.isDetails"
                popup-container="html"
                class="bacClass"
                allow-search
                allowClear
                v-model.trim="dataForm.grade"
              >
                <a-option value="A">A</a-option>
                <a-option value="B">B</a-option>
                <a-option value="C">C</a-option>
                <a-option value="D">D</a-option>
                <a-option value="B/C">B/C</a-option>
              </a-select>
            </a-form-item>

            <a-form-item
              :style="{ width: '1493px' }"
              label-col-flex="100px"
              label="备注"
              field="remark"
              :disabled="pageData.isDetails"
            >
              <a-textarea
                class="bacClass"
                placeholder=""
                v-model="dataForm.remark"
                :max-length="400"
                allow-clear
                show-word-limit
              />
            </a-form-item>
          </a-form>

          <!--          <a-space style="margin-bottom: 10px" v-if="!pageData.isDetails">-->
          <!--            <a-button type="primary" @click="addLine" size="mini">新增</a-button>-->
          <!--            <a-button type="primary" @click="delLine" size="mini">删除</a-button>-->
          <!--          </a-space>-->
        </el-scrollbar>
        <div :style="{ height: '100%', padding: '10px' }">
          <div style="width: 100%; height: 70%">
            <encapsulation-agrid ref="table2Ref" :configaggrid="configTable2"></encapsulation-agrid>
          </div>
        </div>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    usePagination,
    useRowKey,
    useRowSelection,
    useTable,
    useTableColumn,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { nextTick, onMounted, reactive, ref } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import validate from '@/hooks/useValidate'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import usePermission from '@/store/modules/permission'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  import EncapsulationAgrid from '@/components/encapsulationAgrid/encapsulationAgrid.vue'
  import buttionRender from '@/components/aggridCellRenDerer/buttionRender.vue'
  import { fa } from 'element-plus/es/locale'

  interface Cloth {
    merceryCode: string
  }

  interface ClothInfo {
    cylinderCardNumber: string | undefined
    fixedAssetsCode: string | undefined
    compileDate: any
    scDate: string | undefined
    applicableModels: string | undefined
    workDrumCode: string | undefined
    sumNeedleNum: any
    brand: string | undefined
    place: string | undefined
    model: string | undefined
    placeStorage: string | undefined
    applyPin: string | undefined
    applyBranch: string | undefined
    remark: string | undefined
    machine: string | undefined
    ckDate: string | undefined
    rkDate: string | undefined
    applySky: any
    deleteState: any
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    id: any
    list: any[]
    useFrim: any
    frimName: any
    smallNumber: any
    numberThreads: any
    sumWay: any
    applyBranchId: any
    grade: any
  }

  export default {
    name: 'NeedleCylinderEquipment',
    setup() {
      const pageData = reactive<{
        clothList: Cloth[]
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        theight: number
        tablediv: any
        rHeight: number | undefined
        btnList: any[]
        isEdit: boolean
        codeList: any[]
        jtList: any[]
        pbList: any[]
        dropDownData1: any
        firmListsy: any
        bmListsy: any
        isDetails: boolean
        nameList12: []
        nameList13: []
        firmGroupList: any[]
        bmList: any[]
        title: any
        title1: any
        fixedAssetsCode: any
      }>({
        clothList: [],
        showAdd: false,
        sideTitle: '新增针筒设备维护',
        dropDownData: '',
        pageLoading: false,
        theight: 0,
        tablediv: null,
        rHeight: 0,
        btnList: [],
        isEdit: false,
        codeList: [],
        jtList: [],
        pbList: [],
        dropDownData1: '',
        firmListsy: '',
        bmListsy: '',
        isDetails: false,
        nameList12: [],
        nameList13: [],
        firmGroupList: [],
        bmList: [],
        title: '',
        title1: '',
        fixedAssetsCode: '',
      })
      const table1Ref = ref<any>(null)
      const table2Ref = ref<any>(null)
      const edit = (record: any) => {
        selCxAll1({ machineName: '', deleteState: 0 })
        post({
          url: 'product/workdrumEquipment/selectSon',
          data: { id: record.id },
        }).then(({ code, message, data }: any) => {
          if (code === 200) {
            for (var key in record) {
              if (key != 'list') {
                if (key == 'numberThreads' || key == 'smallNumber' || key == 'sumNeedleNum') {
                  dataForm[key] = Number(record[key])
                } else {
                  dataForm[key] = record[key]
                }
              }
            }
            pageData.sideTitle = '修改针筒设备维护'
            pageData.showAdd = true
            pageData.isEdit = true
            pageData.isDetails = false
            getFirmGroup()
            getBmGroup(record.useFrim)
            nextTick(() => {
              table2Ref.value.setdataListIterface(data)
            })
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      }
      const detail = (record: any) => {
        pageData.isDetails = true
        pageData.isEdit = false
        post({
          url: 'product/workdrumEquipment/selectSon',
          data: { id: record.id },
        }).then(({ code, message, data }: any) => {
          if (code === 200) {
            for (var key in record) {
              if (key != 'list') {
                if (key == 'numberThreads' || key == 'smallNumber' || key == 'sumNeedleNum') {
                  dataForm[key] = Number(record[key])
                } else {
                  dataForm[key] = record[key]
                }
              }
            }
            dataForm['list'] = data
            pageData.showAdd = true
            nextTick(() => {
              table2Ref.value.setdataListIterface(dataForm.list)
            })
            getFirmGroup()
            getBmGroup(record.useFrim)
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      }
      const tableColumns = [
        {
          headerCheckboxSelection: true,
          checkboxSelection: true,
          width: 60,
          showDisabledCheckboxes: false,
          pinned: 'left',
        },
        {
          headerName: '序号',
          field: 'id',
          width: 150,
        },
        {
          headerName: '公司',
          field: 'frimName',
          width: 150,
        },
        {
          headerName: '固定资产编号',
          field: 'fixedAssetsCode',
          width: 150,
        },
        {
          headerName: '编制日期',
          field: 'compileDate',
          width: 150,
        },

        {
          headerName: '针筒卡号',
          field: 'cylinderCardNumber',
          width: 150,
        },
        {
          headerName: '存放位置',
          field: 'placeStorage',
          width: 150,
        },
        {
          headerName: '型号',
          field: 'model',
          width: 150,
        },
        {
          headerName: '适用针型',
          field: 'applyPin',
          width: 150,
        },

        {
          headerName: '适用设备机型',
          field: 'applicableModels',
          width: 150,
        },
        {
          headerName: '寸数',
          field: 'smallNumber',
          width: 150,
        },
        {
          headerName: '针数',
          field: 'numberThreads',
          width: 150,
        },
        {
          headerName: '总针数',
          field: 'sumNeedleNum',
          width: 150,
        },
        {
          headerName: '品牌',
          field: 'brand',
          width: 150,
        },
        {
          headerName: '产地',
          field: 'place',
          width: 150,
        },
        {
          headerName: '采购公司',
          field: 'frimName',
          width: 150,
        },
        {
          headerName: '采购部门',
          field: 'applyBranch',
          width: 150,
        },
        {
          headerName: '生产日期',
          field: 'scDate',
          dataIndex: 'scDate',
          width: 150,
        },
        {
          headerName: '等级',
          field: 'grade',
          dataIndex: 'grade',
          width: 150,
        },
        {
          headerName: '创建人',
          field: 'createName',
          width: 150,
        },
        {
          headerName: '创建时间',
          field: 'createTime',
          width: 200,
        },
        {
          headerName: '最后修改人',
          field: 'updateName',
          width: 150,
        },
        {
          headerName: '最后修改时间',
          field: 'updateTime',
          width: 200,
        },
        {
          headerName: '操作',
          field: 'action',
          slotName: 'action',
          resizable: false,
          filter: false,
          sortable: false,
          cellRenderer: buttionRender,
          cellRendererParams: {
            buttonList: [
              {
                type: 'primary',
                text: '修改',
                typeName: 'el-button',
                show: true,
                Callback: (data: any) => {
                  edit(data)
                },
              },
              {
                type: 'primary',
                text: '详情',
                typeName: 'el-button',
                show: true,
                Callback: (data: any) => {
                  detail(data)
                },
              },
            ],
            eltagSize: 0,
          },
          width: 150,
          pinned: 'right',
        },
      ]
      const tableColumns2 = [
        {
          headerCheckboxSelection: true,
          checkboxSelection: true,
          width: 60,
          showDisabledCheckboxes: false,
          pinned: 'left',
        },
        {
          headerName: '机台',
          field: 'machine',
          width: 250,
          slotName: 'machine',
          cellRenderer: {
            template: `
            <a-select popup-container="html" class="bacClass" :loading="loading1" :allowClear="true"
                      @search="callHandleSearch1"
                      :disabled="pageData.isDetails" v-model="record.machine" :filter-option="false" allow-search
                      @focus="callFocusSel1" @change="callJtChange(record, record.machine)">
              <a-option v-for="item in pageData.jtList" :value="item">{{ item }}</a-option>
            </a-select>`,
            setup(props: any) {
              const record = ref(props.params.data)
              const callHandleSearch1 = (value: any) => {
                handleSearch1(value)
              }
              const callFocusSel1 = () => {
                focusSel1()
              }
              const callJtChange = (a: any, b: any) => {
                jtChange(a, b)
              }
              return {
                record,
                callHandleSearch1,
                callFocusSel1,
                callJtChange,
                loading1,
                pageData,
              }
            },
          },
        },
        {
          headerName: '出库日期',
          field: 'ckDate',
          width: 250,
          slotName: 'ckDate',
          cellRenderer: {
            template: `
            <a-date-picker popup-container="html" class="bacClass" style="width: 200px" v-model="record.ckDate"
                           :disabled="pageData.isDetails"/>
          `,
            setup(props: any) {
              const record = ref(props.params.data)
              return {
                record,
                pageData,
              }
            },
          },
        },
        {
          headerName: '入库日期',
          field: 'rkDate',
          width: 250,
          slotName: 'rkDate',
          cellRenderer: {
            template: `
            <a-date-picker popup-container="html" class="bacClass" style="width: 200px" v-model="record.rkDate"
                           placeholder=" " :disabled="pageData.isDetails"/>
          `,
            setup(props: any) {
              const record = ref(props.params.data)
              return {
                record,
                pageData,
              }
            },
          },
        },

        {
          headerName: '适用天数',
          field: 'applySky',
          width: 250,
          slotName: 'applySky',
          cellRenderer: {
            template: `
            <a-input-number v-model="record.applySky" class="bacClass input-demo" :min="0" :max="1000000000000"
                            :disabled="pageData.isDetails"/>
          `,
            setup(props: any) {
              const record = ref(props.params.data)
              return {
                record,
                pageData,
              }
            },
          },
        },
        {
          headerName: '备注',
          field: 'remark',
          width: 350,
          slotName: 'remark',
          cellRenderer: {
            template: `
            <a-textarea class="bacClass" :class="{ bacClass: !pageData.isDetails }" placeholder=""
                        v-model="record.remark" auto-size :max-length="400" allow-clear show-word-limit
                        :disabled="pageData.isDetails"/>
          `,
            setup(props: any) {
              const record = ref(props.params.data)
              return {
                record,
                pageData,
              }
            },
          },
        },
      ]
      let configTable1 = {
        url: 'product/workdrumEquipment/selectWorkdrumEquipmentPage', //接口路径
        queryData: {
          //接口参数
          deleteState: 0,
          cylinderCardNumber: pageData.dropDownData,
          applyBranch: pageData.dropDownData1,
          fixedAssetsCode: pageData.fixedAssetsCode,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tableColumns,
        fileName: 'NeedleCylinderEquipment-ztsbwh-1',
      }
      let configTable2 = {
        url: '', //接口路径
        queryData: {
          //接口参数
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: false, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        isRowClickSelect: true,
        column: tableColumns2,
        fileName: 'NeedleCylinderEquipment-ztsbwh-2',
      }
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)

      function PageSize(val: any) {
        console.log(val)
        page.value = val
        doRefresh()
      }

      function change1(val: any) {
        console.log(val)

        size.value = val
        doRefresh()
      }

      const headerShow = ref<boolean>(true)
      //查询
      const scrollbar = ref(true)

      function doRefresh() {
        table1Ref.value.setQuery({
          deleteState: 0,
          cylinderCardNumber: pageData.dropDownData,
          applyBranch: pageData.dropDownData1,
          fixedAssetsCode: pageData.fixedAssetsCode,
        })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const selectedRowKeysCf = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //检验表单是否含有中文的方法
      const hasChiese = validate.includeChinese
      const scroll = {
        x: 2000,
        y: 200,
      }
      const tablediv = ref(null)
      //下拉框得到焦点
      const focusSel = (ob: any) => {
        selCxAll(ob)
      }
      //下拉数据
      const options = ref<any>(pageData.clothList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { cylinderCardNumber: value, deleteState: 0 }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.clothList
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: '/product/workdrumEquipment/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.clothList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      //机台下拉框
      //下拉框得到焦点
      const focusSel1 = () => {
        selCxAll1({ machineCode: '', deleteState: 0 })
      }
      //下拉数据
      const options1 = ref<any>(pageData.jtList)
      const loading1 = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { machineCode: value, deleteState: 0 }
          loading1.value = true
          selCxAll1(ob)
          options1.value = pageData.jtList
          loading1.value = false
        } else {
          options1.value = []
        }
      }

      //下拉框查询
      function selCxAll1(val: any) {
        post({
          url: 'planSingle/machine/getFieldValue1',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.jtList = data.map(function (item: any) {
              return item['machineCode'] + '——' + item['machineName']
            })
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      onMounted(() => {
        // doRefresh()
        initialization()
        // 切换tap到本页面执行的方法
        emitter.on('NeedleCylinderEquipment', () => {
          initialization()
          // selCxAll({});
        })
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight

        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
        window.addEventListener('resize', () => {
          pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
          //弹出层的高
          if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 100
          }
        })
        // foucusUseFrim(1)
      })
      let cxbl = ''
      //查询
      const selectHandler = () => {
        page.value = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        pageData.isDetails = false
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key == 'list') {
            dataForm[key] = []
          } else if (key == 'sumNeedleNum' || key == 'applySky') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        getFirmGroup()
        pageData.showAdd = true
        pageData.sideTitle = '新增针筒设备维护'
      }
      const dataForm = reactive<ClothInfo>({
        cylinderCardNumber: '',
        fixedAssetsCode: '',
        compileDate: '',
        scDate: '',
        applicableModels: '',
        workDrumCode: '',
        sumNeedleNum: '',
        brand: '',
        place: '',
        model: '',
        placeStorage: '',
        applyPin: '',
        applyBranch: '',
        remark: '',
        machine: '',
        ckDate: '',
        rkDate: '',
        applySky: 0,
        deleteState: 0,
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        id: null,
        list: [],
        useFrim: '',
        frimName: '',
        smallNumber: '',
        numberThreads: '',
        sumWay: '',
        applyBranchId: '',
        grade: '',
      })
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            dataForm.list.forEach(function (o: any) {
              if ((o['id'] + '').indexOf('add') != -1) {
                o['id'] = null
              }
              // o['machine']=o['machine'].split('——')[1]
            })
            pageData.pageLoading = true
            if (pageData.sideTitle === '新增针筒设备维护') {
              post({
                url: 'product/workdrumEquipment/insert',
                data: dataForm,
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()

                    pageData.showAdd = false

                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else {
              post({
                url: '/product/workdrumEquipment/update',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false

                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          draggable: true,
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'product/workdrumEquipment/delete',
              // data: selectedRowKeys.value,
              data: table1Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, message }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const editHandler = (record: ClothInfo, num: any) => {
        selCxAll1({ machineName: '', deleteState: 0 })
        if (num == 2) {
          pageData.isDetails = true
        } else {
          pageData.isDetails = false
        }
        post({
          url: 'product/workdrumEquipment/selectSon',
          data: { id: record.id },
        }).then(({ code, message, data }: any) => {
          if (code === 200) {
            for (var key in record) {
              if (key != 'list') {
                if (key == 'numberThreads' || key == 'smallNumber' || key == 'sumNeedleNum') {
                  dataForm[key] = Number(record[key])
                } else {
                  dataForm[key] = record[key]
                }
              }
            }
            dataForm['list'] = data
            pageData.sideTitle = '修改针筒设备维护'
            pageData.showAdd = true
            getFirmGroup()
            getBmGroup(record.useFrim)
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
          if (reg.test(value)) {
            cb('填写的值不能包含中文！')
          }
          // if (window.encodeURI(value).indexOf('%') !== -1) {
          //     cb('填写的值不能包含中文！')
          // }
          // let pattern = /[a-zA-Z]/;
          // if (pattern.test(value)) {
          //     cb('填写的值只能是数字或特殊字符！')
          // }

          resolve()
        })
      }
      //判断是否填写了中文
      const isChiese1 = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
          if (reg.test(value)) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const inputBlur = () => {
        // dataForm.merceryCode = dataForm.merceryCode.toUpperCase();
      }
      //导出
      const exports = () => {
        let outRow = table1Ref.value.getSelectedRows()
        if (outRow.length === 0) {
          Message.error('请先勾选')
          return
        } else {
          //拿到勾选的主表id
          let idList: any = []
          let tempRow: any = []
          for (let i = 0; i < outRow.length; i++) {
            idList.push(outRow[i]['id'])
          }
          post({
            url: 'product/workdrumEquipment/selectFson',
            data: idList,
          }).then((res: any) => {
            if (res.code == 200) {
              tempRow = res.data
              //将表头拼接出来
              let head = '<th>序号</th><th>固定资产编号</th><th>编制日期</th>'
              head +=
                '<th>针筒卡号</th><th>存放位置</th><th>型号</th><th>适用针型</th><th>适用机型</th><th>寸数</th><th>针数</th><th>总针数</th><th>品牌</th><th>产地</th><th>采购公司</th><th>采购部门</th>'
              head +=
                '<th>生产日期</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'

              let nowRow: any = []
              tempRow.forEach(function (o: any) {
                if (o['component'].length > 0) {
                  o['component'].forEach(function (e: any) {
                    let ob = Object.assign(e, o)
                    nowRow.push(ob)
                  })
                } else {
                  nowRow.push(o)
                }
              })
              console.log(nowRow)

              let body = ''
              console.log(nowRow)
              nowRow.forEach(function (o: any) {
                body += '<tr><td>' + o['id'] + '</td>'
                body +=
                  '<td>' + (o['fixedAssetsCode'] == undefined ? '' : o['fixedAssetsCode']) + '</td>'
                body += '<td>' + (o['compileDate'] == undefined ? '' : o['compileDate']) + '</td>'
                body +=
                  '<td>' +
                  (o['cylinderCardNumber'] == undefined ? '' : o['cylinderCardNumber']) +
                  '</td>'
                body += '<td>' + (o['placeStorage'] == undefined ? '' : o['placeStorage']) + '</td>'
                body += '<td>' + (o['model'] == undefined ? '' : o['model']) + '</td>'
                body += '<td>' + (o['applyPin'] == undefined ? '' : o['applyPin']) + '</td>'
                body +=
                  '<td>' +
                  (o['applicableModels'] == undefined ? '' : o['applicableModels']) +
                  '</td>'
                body += '<td>' + (o['smallNumber'] == undefined ? '' : o['smallNumber']) + '</td>'
                body +=
                  '<td>' + (o['numberThreads'] == undefined ? '' : o['numberThreads']) + '</td>'
                body += '<td>' + (o['sumNeedleNum'] == undefined ? '' : o['sumNeedleNum']) + '</td>'
                body += '<td>' + (o['brand'] == undefined ? '' : o['brand']) + '</td>'
                body += '<td>' + (o['place'] == undefined ? '' : o['place']) + '</td>'
                body += '<td>' + (o['frimName'] == undefined ? '' : o['frimName']) + '</td>'
                body += '<td>' + (o['applyBranch'] == undefined ? '' : o['applyBranch']) + '</td>'
                body += '<td>' + (o['scDate'] == undefined ? '' : o['scDate']) + '</td>'
                body += '<td>' + (o['createName'] == undefined ? '' : o['createName']) + '</td>'
                body += '<td>' + (o['createTime'] == undefined ? '' : o['createTime']) + '</td>'
                body += '<td>' + (o['updateName'] == undefined ? '' : o['updateName']) + '</td>'
                body += '<td>' + (o['updateTime'] == undefined ? '' : o['updateTime']) + '</td>'
                body += '</tr>'
              })
              tableToXlsx(head, '针筒设备维护', body)
            }
          })
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/product/mercery/uploadMerceryModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '针筒设备维护.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      let idToData: any[] = []
      let c = 0
      //成分添加一行 点击新增按钮
      const addLine = () => {
        //在这个数组前面添加一行
        dataForm.list.unshift({
          id: 'add' + c++,
          ckDate: '',
          rkDate: '',
          applySky: 0,
          machine: '',
          remark: '',
          add: true,
        })
        console.log('dataForm.list', dataForm.list)
        setTimeout(() => {
          table2Ref.value.setdataListIterface(dataForm.list)
        }, 100)
      }

      //成分 删除
      const delLine = () => {
        if (table2Ref.value.getSelectedRows().length === 0) {
          Message.error({
            content: '请先勾选',
            duration: 5000,
          })
          return
        }
        const selectRowIds = table2Ref.value.getSelectedRows().map((o: any) => {
          return o.id
        })
        const residueRow = table2Ref.value.getListData().filter((item: any) => {
          return selectRowIds.indexOf(item.id) === -1
        })

        table2Ref.value.setdataListIterface(residueRow)
      }
      //新增坯布信息的下拉框
      //下拉框得到焦点
      const focusSel2 = (ob: any) => {
        selCxAll2(ob)
      }
      //下拉数据
      const options2 = ref<any>(pageData.jtList)
      const loading2 = ref(false)
      const handleSearch2 = (value: any) => {
        if (value) {
          const ob = { machineName: value }
          loading2.value = true
          selCxAll2(ob)
          options2.value = pageData.jtList
          loading2.value = false
        } else {
          options2.value = []
        }
      }

      //下拉框查询
      function selCxAll2(val: any) {
        post({
          url: 'product/pdGreyInformation/selectpdGreyInformation',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.pbList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      //机台下拉框值改变
      const jtChange = (record: any, val: any) => {
        let lis = table2Ref.value.getListData().filter(function (o: any) {
          return o['machine'] == val
        })
        if (lis.length > 1) {
          record.machine = ''
          Message.warning({
            content: '请不要重复选择同一个机台！',
            duration: 5000,
          })
        }
      }
      const options3 = ref(pageData.firmListsy)
      const loading3 = ref(false)

      const handleSearch3 = (value: any) => {
        if (value) {
          loading1.value = true

          options1.value = pageData.firmListsy
          loading1.value = false
        } else {
          options1.value = []
        }
      }
      //公司改变 部门为=空
      const changeGs = (num: any) => {
        dataForm.applyBranch = ''
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)

      //根据寸数/针数/总针数 得出型号
      function getModel() {
        if (
          dataForm.smallNumber != '' &&
          dataForm.smallNumber != null &&
          dataForm.numberThreads != '' &&
          dataForm.numberThreads != null &&
          dataForm.sumNeedleNum != '' &&
          dataForm.sumNeedleNum != null &&
          dataForm.sumNeedleNum != undefined
        ) {
          // dataForm.model = dataForm.smallNumber + dataForm.numberThreads + dataForm.sumNeedleNum
          dataForm.model =
            dataForm.smallNumber + '"' + dataForm.numberThreads + 'G' + dataForm.sumNeedleNum + 'T'
        }
      }

      //品牌名称下拉框得到焦点
      const focusSel12 = () => {
        selCxAll12({ brandName: '', deleteState: 0 })
      }
      //品牌名称下拉数据
      const options12 = ref<any>(pageData.nameList12)
      const loading12 = ref(false)
      const handleSearch12 = (value: any) => {
        if (value) {
          const ob = { brandName: value, deleteState: 0 }
          loading12.value = true
          selCxAll12(ob)
          options12.value = pageData.nameList12
          loading12.value = false
        } else {
          options12.value = []
        }
      }

      //品牌名称下拉框查询
      function selCxAll12(val: any) {
        post({
          url: 'product/Brand/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            let dataList: any = []
            data.forEach(function (o: any) {
              dataList.push(o['brandName'])
            })
            pageData.nameList12 = dataList
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const focusSel13 = () => {
        selCxAll13({ typeName: '', deleteState: 0 })
      }
      //品牌名称下拉数据
      const options13 = ref<any>(pageData.nameList13)
      const loading13 = ref(false)
      const handleSearch13 = (value: any) => {
        if (value) {
          const ob = { typeName: value, deleteState: 0 }
          loading13.value = true
          selCxAll13(ob)
          options13.value = pageData.nameList13
          loading13.value = false
        } else {
          options13.value = []
        }
      }

      //品牌名称下拉框查询
      function selCxAll13(val: any) {
        post({
          url: 'planSingle/machineType/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            let dataList: any = []
            data.forEach(function (o: any) {
              dataList.push(o['typeName'])
            })
            pageData.nameList13 = dataList
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const huiche = () => {
        doRefresh()
      }
      const huiche2 = () => {
        doRefresh()
      }
      const casOb = ref()
      const casOb1 = ref()
      //公司改变
      const cascaderChange = (event: any, val: any) => {
        dataForm.applyBranchId = null
        //拿到选中的这个节点数组
        setTimeout(function () {
          if (casOb.value.selectViewValue.length != 0) {
            pageData.title = slicing(casOb.value.selectViewValue[0]['label'])
            dataForm.frimName = slicing(casOb.value.selectViewValue[0]['label'])
          }
        }, 100)
        getBmGroup(val)
      }
      //部门改变
      const cascaderChange1 = (val: any) => {
        //拿到选中的这个节点数组
        setTimeout(function () {
          if (casOb1.value.selectViewValue.length != 0) {
            pageData.title1 = slicing(casOb1.value.selectViewValue[0]['label'])
            dataForm.applyBranch = slicing(casOb1.value.selectViewValue[0]['label'])
            dataForm.applyBranchId = casOb1.value.selectViewValue[0]['value']
            console.log(casOb1.value.selectViewValue)
          }
        }, 100)
      }
      // 获取部门列表
      const getBmGroup = (val?: any) => {
        post({
          url: 'org/baCompany/getDepartmentTree?companyId=' + val,
        }).then((result) => {
          if (result.code === 200) {
            pageData.bmList = result.data
          }
        })
      }
      // 获取公司列表
      const getFirmGroup = () => {
        post({
          url: 'org/baCompany/getTreeCompanyByUser',
          data: {},
        }).then(({ code, data }) => {
          if (code === 200) {
            pageData.firmGroupList = data
          }
        })
      }

      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('ztsbwh.cx')) {
        pageData.btnList.push('查询')
      }
      // if (permissionStore.hasPermisson('ztsbwh.xz')) {
      //   pageData.btnList.push('新增')
      // }
      if (permissionStore.hasPermisson('ztsbwh.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('ztsbwh.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('ztsbwh.xg')) {
        pageData.isEdit = true
      }
      if (permissionStore.hasPermisson('ztsbwh.xq')) {
        pageData.isDetails = true
      }
      // 针筒设备初始化表
      const initialization = () => {
        get({
          url: 'product/workdrumEquipment/initialization',
          data: {},
        })
          .then(({ code, data, message }) => {
            if (code === 200) {
            } else {
              Message.error({
                content: message,
                duration: 5000,
              })
            }
          })
          .finally(() => {
            doRefresh()
          })
      }
      return {
        colState,
        permissionStore,
        casOb,
        casOb1,
        cascaderChange1,
        cascaderChange,
        pagingList1,
        huiche,
        huiche2,
        handleSearch13,
        focusSel13,
        handleSearch12,
        focusSel12,
        isChiese1,
        isChiese,
        getModel,
        localeText1,
        defaultColDef,
        gridOption,
        gridReady,
        // foucusUseFrim,
        options3,
        loading3,
        handleSearch3,
        changeGs,
        total,
        PageSize,
        change1,
        page,
        size,
        scroll,
        scrollbar,
        tablediv,
        downloadHandler,
        importHandler,
        hasChiese,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        editHandler,
        selectHandler,
        options,
        loading,
        handleSearch,
        options1,
        loading1,
        handleSearch1,
        focusSel1,
        options2,
        loading2,
        handleSearch2,
        focusSel2,
        inputBlur,
        exports,
        focusSel,
        headerShow,
        addLine,
        delLine,
        s: selectedRowKeysCf.selectedRowKeys,
        jtChange,
        handleChange,
        table1Ref,
        configTable1,
        table2Ref,
        configTable2,
        tableColumns2,
      }
    },
    components: { EncapsulationAgrid, Toolbar,  },
  }
</script>
